package com.dwxt.mall.admin.service;

import com.dwxt.common.base.*;
import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.ExcelUtils;
import com.dwxt.common.util.JsonUtils;
import com.dwxt.mall.admin.service.feign.AdminUserService;
import com.dwxt.mall.constant.OrderStatus;
import com.dwxt.mall.dao.OrderActionLogMapper;
import com.dwxt.mall.dao.PayOrderMapper;
import com.dwxt.mall.entity.OrderActionLog;
import com.dwxt.mall.entity.PayOrder;
import com.dwxt.mall.entity.PayOrderExample;
import com.dwxt.mall.entity.ReceiptAddress;
import com.dwxt.mall.entity.vo.OrderVO;
import com.dwxt.mall.service.feign.PayService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceAdmin {
    @Autowired
    private PayOrderMapper orderMapper;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private PayService payService;

    @Autowired
    private OrderActionLogMapper orderActionLogMapper;

    public List<PayOrder> selectOrderList(PayOrder order, String startTime, String endTime, Integer isSuccess) {

        PayOrderExample example = new PayOrderExample();
        example.setOrderByClause("create_time desc");
        PayOrderExample.Criteria criteria = example.createCriteria();
        //订单编号查询
        if (StringUtils.isNotBlank(order.getId())) {
            criteria.andIdEqualTo(order.getId());
        }
        //由名称查询
        if (StringUtils.isNotBlank(order.getName())) {
            criteria.andNameLike("%" + order.getName() + "%");
        }
        //由状态查询
        if (StringUtils.isNotBlank(order.getStatus())) {
            criteria.andStatusEqualTo(order.getStatus());
        } else {
            criteria.andStatusNotEqualTo(OrderStatus.CANCEL).andStatusNotEqualTo(OrderStatus.PLACE);
        }
        //由供货商查询
        if (order.getSupplierId() != null) {
            criteria.andSupplierIdEqualTo(order.getSupplierId());
        }
        //由券码查询
        if (StringUtils.isNotBlank(order.getTicketCode())) {
            criteria.andTicketCodeEqualTo(order.getTicketCode());
        }

        if (StringUtils.isNotBlank(order.getCategory())) {
            criteria.andCategoryEqualTo(order.getCategory());
        }

        if (StringUtils.isNotBlank(startTime)) {
            criteria.andCreateTimeBetween(DateUtils.formatTime(startTime), DateUtils.formatTime(endTime));
        }

        if (isSuccess != null && isSuccess == 1) {
            //支付成功的订单状态
            List<String> list = new ArrayList<>();
            list.add(OrderStatus.REFUND_FAIL);
            list.add(OrderStatus.PAY);
            list.add(OrderStatus.SHIP);
            list.add(OrderStatus.RECEIPT);
            list.add(OrderStatus.REQUEST_REFUND);
            list.add(OrderStatus.REFUND_FAIL);
            criteria.andStatusIn(list);
        }
        //是否是商家账户
        //BaseResult baseResult = adminUserService.selectUser();
        JSONObject user = JSONObject.fromObject(adminUserService.selectUser().getData());
        if (!user.getString("type").contains(AdminUserType.ADMIN)) {
            criteria.andSupplierIdEqualTo(user.getInt("id"));
        }
        return orderMapper.selectByExample(example);
    }

    public int ship(String id) {
        List<String> list = new ArrayList<>();
        list.add(OrderStatus.PAY);
        list.add(OrderStatus.REFUND_FAIL);
        //list.add(OrderStatus.REQUEST_REFUND);
        PayOrder order = orderMapper.selectByPrimaryKey(id);
        if (order.getProductStatus() == null && list.contains(order.getStatus())) {
            BaseResult baseResult = adminUserService.selectUser();
            Map data = (Map) baseResult.getData();
            int userId = Integer.parseInt(data.get("id").toString());
            String username = data.get("username").toString();

            generateOrderLog("SUCCESS", userId, username, "发货");
            //order.setStatus(OrderStatus.SHIP);
            order.setProductStatus(OrderStatus.SHIP);
            return orderMapper.updateByPrimaryKey(order);
        } else {
            return 0;
        }
    }

    public PayOrder selectOrder(String id) {
        PayOrder order = orderMapper.selectByPrimaryKey(id);
        if (order.getAddressId() == 0) {
            return order;
        }
        //订单增加地址信息，修改后兼容老版本
        if (StringUtils.isNotBlank(order.getAddress())) {
            ReceiptAddress address = new ReceiptAddress();
            address.setUsername(order.getUsername());
            address.setPhone(order.getPhone());
            address.setAddress(order.getAddress());
            OrderVO orderVO = JsonUtils.jsonToPojo(JsonUtils.objectToJson(order), OrderVO.class);
            orderVO.setReceiptAddress(address);
            return orderVO;
        } else {
            return orderMapper.selectOrder(id);
        }
    }

    public BaseResult refund(String orderId, String reason, String status) throws Exception {
        List<String> list = new ArrayList<>();
        list.add(OrderStatus.PAY);
        list.add(OrderStatus.SHIP);
        list.add(OrderStatus.RECEIPT);
        list.add(OrderStatus.REQUEST_REFUND);
        list.add(OrderStatus.REFUND_FAIL);
        PayOrder order = orderMapper.selectByPrimaryKey(orderId);
        if (!list.contains(order.getStatus())) {
            return BaseResult.build(StatusCode.REFUND_ERROR);
        } else {
            BaseResult result = adminUserService.selectUser();
            Map data = (Map) result.getData();
            int userId = Integer.parseInt(data.get("id").toString());
            String username = data.get("username").toString();

            //同意申请退款
            if (status.equalsIgnoreCase("success")) {
                BaseResult baseResult;
                if (order.getRealPrice() == 0) {
                    status = OrderStatus.REFUND;
                } else {
                    if (order.getPayMethod().equalsIgnoreCase(PurchaseMethod.WX)) {
                        baseResult = payService.wxRefund(order.getId(), order.getRealPrice());
                    } else {
                        baseResult = payService.zfbRefund(order.getId(), order.getRealPrice());
                    }
                    if (baseResult.getStatus() == 200 && "SUCCESS".equalsIgnoreCase(baseResult.getData().toString())) {
                        status = OrderStatus.REFUND;
                    } else {
                        status = OrderStatus.REFUND_FAIL;
                    }
                }
                generateOrderLog(status, userId, username, "同意退款");
            } else {
                //拒绝退款
                status = OrderStatus.REFUND_FAIL;
                generateOrderLog(status, userId, username, "拒绝退款");
            }
        }
        //更改订单状态
        order.setCheckReason(reason);
        order.setStatus(status);
        orderMapper.updateByPrimaryKeySelective(order);
        return BaseResult.ok();
    }

    private void generateOrderLog(String status, int userId, String username, String action) {
        OrderActionLog orderActionLog = new OrderActionLog();
        orderActionLog.setAction(action);
        orderActionLog.setUserId(userId);
        orderActionLog.setUsername(username);
        orderActionLog.setResult(status);
        orderActionLogMapper.insertSelective(orderActionLog);
    }

    public void exportOrder(HttpServletResponse response, PayOrder order, String startTime, String endTime, Integer isSuccess) {
        List<PayOrder> list = selectOrderList(order, startTime, endTime, isSuccess);

        if (ObjectUtils.isNotEmpty(list)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //excel标题
            String[] title = {"订单编号", "商品名", "购买数量", "积分", "价格", "支付方式", "商品类型", "订单状态", "发货状态", "创建时间"};

            //excel文件名
            String fileName = "订单明细表" + System.currentTimeMillis() + ".xls";

            //sheet名
            String sheetName = "订单明细表";
            String[][] content = new String[list.size()][10];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                PayOrder payOrder = list.get(i);
                content[i][0] = payOrder.getId();
                content[i][1] = payOrder.getName();
                content[i][2] = payOrder.getNumber().toString();
                content[i][3] = payOrder.getIntegral().toString();
                content[i][4] = payOrder.getRealPrice().toString();
                content[i][5] = payOrder.getPayMethod();
                content[i][6] = payOrder.getCategory();
                content[i][7] = payOrder.getStatus();
                content[i][8] = payOrder.getProductStatus() == null ? "未发货" : payOrder.getProductStatus();
                content[i][9] = DateUtils.formatTime(payOrder.getCreateTime());
            }
            //创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
            //响应到客户端
            try {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public BaseResult selectOrderStatistics(Integer year, Integer month) {
        Map map = orderMapper.selectOrderStatistics(year, month);
        return BaseResult.ok(map);
    }

    public BaseResult orderStatistics(String startTime, String endTime) {
        List<Map> mapList = orderMapper.orderStatistics(startTime, endTime);
        return BaseResult.ok(mapList);
    }

    public void exportOrderCategory(HttpServletResponse response, String startTime, String endTime) {
        List<Map> list = orderMapper.orderStatistics(startTime, endTime);

        if (ObjectUtils.isNotEmpty(list)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //excel标题
            String[] title = {"所属模块", "商品类型", "订单数", "销售额"};

            //excel文件名
            String fileName = "订单模块统计表" + System.currentTimeMillis() + ".xls";

            //sheet名
            String sheetName = "订单模块统计表";
            String[][] content = new String[list.size()][4];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Map map = list.get(i);
                content[i][0] = map.get("module").toString();
                content[i][1] = map.get("categoryName").toString();
                content[i][2] = map.get("number").toString();
                content[i][3] = map.get("total").toString();

            }
            //创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
            //响应到客户端
            try {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
